package tcpserver.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import tcpserver.config.TcpServerConfig;
import tcpserver.server.NettyTcpServer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * TCP服务管理服务
 * 
 * 提供TCP服务器的管理、监控和控制功能
 */
@Service
public class TcpServerService {
    
    private static final Logger logger = LoggerFactory.getLogger(TcpServerService.class);
    
    @Autowired
    private NettyTcpServer nettyTcpServer;
    
    @Autowired
    @Qualifier("tcpServerConfig")
    private TcpServerConfig config;
    
    private final Date startTime = new Date();
    
    /**
     * 获取服务器状态信息
     */
    public Map<String, Object> getServerStatus() {
        Map<String, Object> status = new HashMap<>();
        
        status.put("running", nettyTcpServer.isRunning());
        status.put("host", config.getHost());
        status.put("port", config.getPort());
        status.put("currentConnections", nettyTcpServer.getCurrentConnectionCount());
        status.put("startTime", formatDate(startTime));
        status.put("uptime", getUptime());
        status.put("bossThreads", config.getBossThreads());
        status.put("workerThreads", config.getWorkerThreads() > 0 ? 
                  config.getWorkerThreads() : Runtime.getRuntime().availableProcessors() * 2);
        
        return status;
    }
    
    /**
     * 获取服务器详细配置信息
     */
    public Map<String, Object> getServerConfig() {
        Map<String, Object> configMap = new HashMap<>();
        
        configMap.put("host", config.getHost());
        configMap.put("port", config.getPort());
        configMap.put("bossThreads", config.getBossThreads());
        configMap.put("workerThreads", config.getWorkerThreads());
        configMap.put("connectTimeout", config.getConnectTimeout());
        configMap.put("backlog", config.getBacklog());
        configMap.put("tcpNodelay", config.isTcpNodelay());
        configMap.put("keepAlive", config.isKeepAlive());
        configMap.put("reuseAddr", config.isReuseAddr());
        configMap.put("readerIdleTime", config.getReaderIdleTime());
        configMap.put("writerIdleTime", config.getWriterIdleTime());
        configMap.put("allIdleTime", config.getAllIdleTime());
        configMap.put("maxMessageLength", config.getMaxMessageLength());
        configMap.put("sslEnabled", config.isSslEnabled());
        
        return configMap;
    }
    
    /**
     * 重启服务器
     */
    public boolean restartServer() {
        try {
            logger.info("正在重启TCP服务器...");
            
            // 关闭服务器
            nettyTcpServer.shutdown();
            
            // 等待一段时间确保完全关闭
            Thread.sleep(2000);
            
            // 重新启动服务器
            nettyTcpServer.start();
            
            logger.info("TCP服务器重启完成");
            return true;
            
        } catch (Exception e) {
            logger.error("重启TCP服务器失败", e);
            return false;
        }
    }
    
    /**
     * 检查服务器健康状态
     */
    public Map<String, Object> getHealthCheck() {
        Map<String, Object> health = new HashMap<>();
        
        boolean isHealthy = nettyTcpServer.isRunning();
        
        health.put("status", isHealthy ? "UP" : "DOWN");
        health.put("server", nettyTcpServer.getServerInfo());
        health.put("timestamp", formatDate(new Date()));
        
        // 检查资源使用情况
        Runtime runtime = Runtime.getRuntime();
        long maxMemory = runtime.maxMemory();
        long totalMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();
        long usedMemory = totalMemory - freeMemory;
        
        Map<String, Object> memory = new HashMap<>();
        memory.put("max", formatBytes(maxMemory));
        memory.put("total", formatBytes(totalMemory));
        memory.put("used", formatBytes(usedMemory));
        memory.put("free", formatBytes(freeMemory));
        memory.put("usage", String.format("%.2f%%", (double) usedMemory / totalMemory * 100));
        
        health.put("memory", memory);
        
        // 系统信息
        Map<String, Object> system = new HashMap<>();
        system.put("processors", Runtime.getRuntime().availableProcessors());
        system.put("javaVersion", System.getProperty("java.version"));
        system.put("osName", System.getProperty("os.name"));
        system.put("osVersion", System.getProperty("os.version"));
        
        health.put("system", system);
        
        return health;
    }
    
    /**
     * 获取服务器统计信息
     */
    public Map<String, Object> getServerStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        stats.put("currentConnections", nettyTcpServer.getCurrentConnectionCount());
        stats.put("uptime", getUptime());
        stats.put("startTime", formatDate(startTime));
        stats.put("currentTime", formatDate(new Date()));
        
        // 这里可以添加更多统计信息，如：
        // - 总连接数
        // - 消息处理数量
        // - 错误数量
        // - 平均响应时间
        
        return stats;
    }
    
    /**
     * 发送广播消息到所有连接的客户端
     * （需要在TcpServerHandler中实现连接管理）
     */
    public boolean broadcastMessage(String message) {
        try {
            // 这里需要实现向所有连接的客户端发送消息的逻辑
            logger.info("广播消息: {}", message);
            
            // TODO: 实现广播功能
            return true;
            
        } catch (Exception e) {
            logger.error("发送广播消息失败", e);
            return false;
        }
    }
    
    /**
     * 格式化日期
     */
    private String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    
    /**
     * 计算运行时间
     */
    private String getUptime() {
        long uptimeMs = System.currentTimeMillis() - startTime.getTime();
        long seconds = uptimeMs / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;
        
        if (days > 0) {
            return String.format("%d天 %d小时 %d分钟", days, hours % 24, minutes % 60);
        } else if (hours > 0) {
            return String.format("%d小时 %d分钟", hours, minutes % 60);
        } else if (minutes > 0) {
            return String.format("%d分钟 %d秒", minutes, seconds % 60);
        } else {
            return String.format("%d秒", seconds);
        }
    }
    
    /**
     * 格式化字节数
     */
    private String formatBytes(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        } else if (bytes < 1024 * 1024) {
            return String.format("%.2f KB", bytes / 1024.0);
        } else if (bytes < 1024 * 1024 * 1024) {
            return String.format("%.2f MB", bytes / (1024.0 * 1024.0));
        } else {
            return String.format("%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0));
        }
    }
}